import csv
import tkinter as tk
import subprocess

class App:
    def __init__(self, master):
        self.master = master
        self.cu = CsvUtils()

        self.label_NTC = tk.Label(master, text="NTC Choose: " + "None")
        self.label_NTC.pack(anchor='w')

        self.radio_var1 = tk.IntVar()  #NTC选择 10K 100K 50K

        radio_10K = tk.Radiobutton(master, text="10K", variable=self.radio_var1, value=1, command=self.radio_selected_NTC)
        radio_100K = tk.Radiobutton(master, text="100K", variable=self.radio_var1, value=2, command=self.radio_selected_NTC)
        radio_50K = tk.Radiobutton(master, text="50K", variable=self.radio_var1, value=3, command=self.radio_selected_NTC)

        radio_10K.pack(side=tk.TOP,anchor='w')# 使用side=LEFT使按钮水平排列
        radio_100K.pack(side=tk.TOP,anchor='w')# 继续添加到同一行
        radio_50K.pack(side=tk.TOP,anchor='w')# 继续添加到同一行

        self.label_connect = tk.Label(master, text="NTC Postion: " + "None")
        self.label_connect.pack(anchor='w')

        self.radio_var2 = tk.IntVar()   #上下选择 0-GND 1-VCC

        radio_VCC = tk.Radiobutton(master, text="VCC", variable=self.radio_var2, value=1, command=self.radio_selected_connect)
        radio_GND = tk.Radiobutton(master, text="GND", variable=self.radio_var2, value=2, command=self.radio_selected_connect)

        radio_VCC.pack(side=tk.TOP,anchor='w')# 使用side=LEFT使按钮水平排列
        radio_GND.pack(side=tk.TOP,anchor='w')# 继续添加到同一行

        # 创建一个标签，用于显示文本框的内容
        self.label = tk.Label(master, text="RES Choose: None")
        self.label.pack(anchor='w')

        # 创建一个文本框
        self.entry = tk.Entry(master)
        self.entry.pack(side=tk.TOP,anchor='w')

        # 创建一个按钮，当点击时将获取文本框的内容
        get_button = tk.Button(master, text="Enter",command=self.get_input_res)
        get_button.pack(side=tk.TOP,anchor='w')

        # 创建一个标签
        self.label_TempStart = tk.Label(master, text="Temp Start: ")
        self.label_TempStart.pack(side=tk.TOP,anchor='w')

        # 创建一个文本框
        self.entry_TempStart = tk.Entry(master)
        self.entry_TempStart.pack(side=tk.TOP,anchor='w')

        # 创建一个标签
        self.label_TempEnd = tk.Label(master, text="Temp End: ")
        self.label_TempEnd.pack(side=tk.TOP,anchor='w')

        # 创建一个文本框
        self.entry_TempEnd = tk.Entry(master)
        self.entry_TempEnd.pack(side=tk.TOP,anchor='w')

        # 创建一个按钮，当点击时将保存文本框的内容
        get_button_Temp_Section = tk.Button(master, text="Enter",command=self.get_input_Temp_Section)
        get_button_Temp_Section.pack(side=tk.TOP,anchor='w')    

        # 创建一个按钮，当点击时将生成csv文件并保存
        get_button = tk.Button(master, text="Build CSV",command=self.save_csv)
        get_button.pack(side=tk.TOP,anchor='w')
        
    def radio_selected_NTC(self):
        if self.radio_var1.get() == 1:
            self.label_NTC.config(text="NTC Choose: " + "10K")
        elif self.radio_var1.get() == 2:
            self.label_NTC.config(text="NTC Choose: " + "100K")
        elif self.radio_var1.get() == 3:
            self.label_NTC.config(text="NTC Choose: " + "50K")

    def radio_selected_connect(self):
        if self.radio_var2.get() == 1:
            self.label_connect.config(text="NTC Postion: " + "VCC")
        elif self.radio_var2.get() == 2:
            self.label_connect.config(text="NTC Postion: " + "GND")

    def get_input_res(self):
        if(self.entry.get() == ""):
            self.label.config(text="RES Choose: None")
        else:
            user_input = self.entry.get()  # 获取文本框的内容
            self.label.config(text="RES Choose: " + user_input + "KΩ")  # 将获取的内容显示在Label控件中

    def get_input_Temp_Section(self):
        self.cu.Temp_Start = int(self.entry_TempStart.get())
        self.cu.Temp_End = int(self.entry_TempEnd.get())

    def save_csv(self):
        self.cu.csv_read(self.cu.read_path)
        #获取NTC选择值
        for key, value in self.cu.write_list_index.items():
            if(self.radio_var1.get() == value):
                self.cu.ntc_choose = key
        #获取NTC接地选择值
        if(self.radio_var2.get() == 1):
            self.cu.ntc_postion = 1
        else:
            self.cu.ntc_postion = 0

        res_choose_str = ''
        #获取输入的电阻值
        for str in self.label.cget("text"):
            if str.isdigit() is True:
                res_choose_str += str
            if str == '.':
                res_choose_str += str
        self.cu.res_choose = float(res_choose_str)
        # print(self.cu.res_choose)
        #生成csv文件
        self.cu.csv_write_path_update(f"{self.cu.ntc_choose}.csv")
        self.cu.data_append(self.cu.ntc_choose,self.cu.res_choose,self.cu.Temp_Start,self.cu.Temp_End,self.cu.ntc_postion)
        self.cu.csv_writes(self.cu.write_path, self.cu.write_list)

        #打开生成的csv文件
        subprocess.run(['start', 'WPS Office', self.cu.write_path], shell=True)
class CsvUtils:
    def __init__(self):
        self.read_path = "ntc.csv"
        self.write_path = "data.csv"
        self.read_list = []
        self.write_list = []
        self.write_list_index = {"10K":1,"100K":2,"50K":3}
        self.ntc_choose = '10K'
        self.res_choose = 0.0
        self.Temp_Start = 0
        self.Temp_End = 0
        self.volatage = 0.0
        self.ad_value = 0.0

    #读取CSV文件
    def csv_read(self, file_path):
        # 读取CSV文件
        with open(file_path, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            for row in reader:
                self.read_list.append(row)
    
    #更新写入文件名称
    def csv_write_path_update(self, file_path):
        self.write_path = f"{file_path}"

    #写入多行数据
    def csv_writes(self, file_path, data):
        # 写入CSV文件
        with open(file_path, 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            writer.writerows(data)

    #添加写入数据 ntc值,上下拉电阻值,起始温度,终止温度,ntc位置
    def data_append(self, ntc_choose,res_choose,start_temp,end_temp,ntc_postion):
            self.write_list = []
            self.write_list.append([
                self.read_list[0][0],#Temp
                self.read_list[0][self.write_list_index[ntc_choose]],#ntc选择值
                "Volatage",
                "AD_Value",
                ])
            for i in range(start_temp,end_temp+1):
                if(ntc_postion == 0):#ntc接GND
                    self.volatage = float(self.read_list[i+1][self.write_list_index[ntc_choose]]) / (res_choose + float(self.read_list[i+1][self.write_list_index[ntc_choose]]))
                else:
                    self.volatage = res_choose / (res_choose + float(self.read_list[i+1][self.write_list_index[ntc_choose]]))
                self.ad_value = self.volatage * 4096
                self.write_list.append([
                    i,#Temp
                    self.read_list[i+1][self.write_list_index[ntc_choose]],#ntc选择值
                    self.volatage,
                    int(self.ad_value),
                ])
            # print(self.write_list)


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.title("NTC-ADC Converter")
    root.geometry("150x400")
    root.minsize(150, 400)
    root.maxsize(150, 400)
    root.mainloop()